package org.example.test02.plugin;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorFontType;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.components.JBScrollPane;
import org.example.test02.utils.AliUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class CodeComplement extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 获取当前编辑器
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        //获取当前项目
        Project project = e.getProject();
        if (project == null) {
            Messages.showInfoMessage("No project available.", "Error");
            return;
        }
        if (editor == null) {
            Messages.showInfoMessage("No editor available.", "Error");
            return;
        }

        // 获取当前文件的 PsiFile
        VirtualFile virtualFile = FileEditorManager.getInstance(project).getSelectedFiles()[0];
        PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
        if (psiFile == null) {
            return;
        }

        // 获取选择模型
        String codeBlock = "";
        // 获取文档对象
        Document document = editor.getDocument();
        SelectionModel selectionModel = editor.getSelectionModel();
        if (selectionModel.hasSelection()) {
            // 获取选中的文本
            String selectedText = selectionModel.getSelectedText();
            if (selectedText != null) {
                codeBlock = selectedText;
            }
        } else {
            // 获取光标位置
            CaretModel caretModel = editor.getCaretModel();
            int caretOffset = caretModel.getOffset();
            // 获取当前行号
            int lineNumber = document.getLineNumber(caretOffset);
            // 获取当前行的起始偏移量
            int lineStartOffset = document.getLineStartOffset(lineNumber-2);
            // 获取当前行的代码
            codeBlock =String.format(" %s ",document.getText().substring(lineStartOffset, caretOffset));

        }


        //调用qwen大模型，生成代码推荐
        String complation = AliUtil.getComplation(codeBlock);


        //在光标位置插入多行代码
        EditorTextField editorTextField = new EditorTextField(complation, project, psiFile.getFileType());
        editorTextField.setFont(editor.getColorsScheme().getFont(EditorFontType.PLAIN));
        editorTextField.setBackground(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground());
        editorTextField.setOneLineMode(false);

        System.out.println("构建editor成功");
        System.out.println("返回的数据"+complation);

        // 创建“采纳”按钮
        JButton acceptButton = new JButton("采纳");

        // 创建一个面板，包含 EditorTextField 和“采纳”按钮
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JBScrollPane(editorTextField), BorderLayout.CENTER);
        panel.add(acceptButton, BorderLayout.SOUTH);

        // 创建悬浮窗口
        JBPopup popup = JBPopupFactory.getInstance()
                .createComponentPopupBuilder(panel, null) // 直接传入内容面板
                .setRequestFocus(true) // 允许获取焦点
                .setCancelOnClickOutside(true) // 点击外部关闭
                .setCancelOnWindowDeactivation(true) // 窗口失活关闭
                .setCancelKeyEnabled(true) // 允许按 ESC 关闭
                .setResizable(true)// 根据内容自适应调整框的大小
                .createPopup();

        // 设置按钮的点击事件
        acceptButton.addActionListener(event -> {
            // 获取 EditorTextField 的内容
            String textToInsert = editorTextField.getText();
            // 获取光标位置
            CaretModel caretModel1 = editor.getCaretModel();
            int caretOffset1 = caretModel1.getOffset();

            // 在光标位置插入内容
            WriteCommandAction.runWriteCommandAction(project, () -> {
                document.insertString(caretOffset1, textToInsert);
            });

            // 关闭悬浮窗口
            popup.cancel();
        });

        // 为面板添加键盘事件监听器
        panel.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    // 按下 Enter 键时执行的操作
                    // 获取 EditorTextField 的内容
                    String textToInsert = editorTextField.getText();
                    // 获取光标位置
                    CaretModel caretModel1 = editor.getCaretModel();
                    int caretOffset1 = caretModel1.getOffset();

                    // 在光标位置插入内容
                    WriteCommandAction.runWriteCommandAction(project, () -> {
                        document.insertString(caretOffset1, textToInsert);
                    });
                    popup.closeOk(null); // 关闭弹出窗口
                }
            }
        });



        // 显示悬浮窗口
        popup.showInBestPositionFor(editor);
    }
}
